<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/26
 * Time: 16:47
 */

namespace app\api\controller\v1;


use app\api\validate\CountValidate;
use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\NotFoundException;
use think\Controller;
use app\api\model\Product as ProductModel;

class Product extends Controller
{
    /**
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     * @url /product/recent
     */
    public function getRecentProduct($count=15){
        (new CountValidate())->goCheck();

        $result = ProductModel::getRecentProduct($count);

//        $collection = collection($result); 将数据集转换为对象

        if(!$result){
            throw new NotFoundException();
        }

        return $result;
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|\think\Collection
     * @throws NotFoundException
     * @url /product/category?id=...
     */
    public function getProductByCategory($id){
        (new IDMustBePostiveInt())->goCheck();
        $products = ProductModel::getProductByCategory($id);

        if(!$products){
            throw new NotFoundException();
        }
        return $products;
    }

    /**
     * @param $id
     * @url /product/:id
     */
    public function getOne($id){
        (new IDMustBePostiveInt())->goCheck();
        $product = ProductModel::findById($id);

        if(!$product){
            throw new NotFoundException();
        }
        return $product;
    }

}